import * as vscode from 'vscode';
import * as http from 'http';
import axios from 'axios';
import * as child_process from 'child_process';
import * as pkg from '../package.json';
const EXTENSION_VERSION = pkg.version;

// =====================
// 全局静态常量配置（OAuth/用户相关）
// =====================

/** OAuth 登录页地址 */
const OAUTH_URL = 'http://oauth.cyou-inc.com:8088/oauth/oauth.html';
/** OAuth 回调端口 */
const OAUTH_CALLBACK_PORT = 54321;
/** OAuth 回调路径 */ 
const OAUTH_CALLBACK_PATH = '/oauth-callback';
/** 获取用户信息接口 */
const OAUTH_USERINFO_URL = 'http://oauth.cyou-inc.com:8090/oauth/user/getAccount';
/** 登录超时时间（毫秒，2分钟） */   
const LOGIN_TIMEOUT_MS = 2 * 60 * 1000;

export interface UserInfo {
    account: string;
    name: string;
    oauthtoken: string;
    [key: string]: any;
}


export class AuthService {
    private context: vscode.ExtensionContext;
    private userInfo: UserInfo | null = null;

    constructor(context: vscode.ExtensionContext) {
        this.context = context;
        this.userInfo = context.globalState.get<UserInfo>('userInfo') || null;
    }

    public async getCurrentUser(): Promise<UserInfo | null> {
        this.userInfo = this.context.globalState.get<UserInfo>('userInfo') || null;
        return this.userInfo;
    }

    public async login(): Promise<UserInfo> {
        // 启动本地 HTTP 服务监听回调  $
        const server = http.createServer(async (req, res) => {
            if (req.url && req.url.startsWith(OAUTH_CALLBACK_PATH)) {
                const url = new URL(req.url, `http://localhost:${OAUTH_CALLBACK_PORT}`);
                const oauthtoken = url.searchParams.get('oauthtoken');
                if (oauthtoken) {
                    try {
                        const userInfo = await this.fetchUserInfo(oauthtoken);
                        this.userInfo = userInfo;
                        this.context.globalState.update('userInfo', userInfo);
                        try {
                            // 设置 git 全局用户名和邮箱
                            if (userInfo.account) {
                                child_process.execSync(`git config --global user.name "${userInfo.account}"`);
                                child_process.execSync(`git config --global user.email "${userInfo.account}@cyou-inc.com"`);
                            }
                        } catch (e) {
                            // 忽略 git 配置异常，仅输出日志
                            console.error(`[v${EXTENSION_VERSION}] 设置 git 用户信息失败`, e);
                        }
                        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
                        res.end(`<h2>登录成功，可以关闭此页面</h2><div>插件版本: ${EXTENSION_VERSION}</div>`);
                        server.close();
                    } catch (e) {
                        res.writeHead(500,{ 'Content-Type': 'text/html; charset=utf-8' });
                        res.end(`获取用户信息失败<br/>插件版本: ${EXTENSION_VERSION}`);
                        console.error(`[v${EXTENSION_VERSION}] 获取用户信息失败`, e);
                        server.close();
                    }
                } else {
                    res.writeHead(400,{ 'Content-Type': 'text/html; charset=utf-8' });
                    res.end('缺少 oauthtoken');
                }
            } else {
                res.writeHead(404);
                res.end();
            }
        });
        server.listen(OAUTH_CALLBACK_PORT);

        // 打开 OAuth 登录页面
        const redirectUrl = `http://localhost:${OAUTH_CALLBACK_PORT}${OAUTH_CALLBACK_PATH}`;
        const loginUrl = `${OAUTH_URL}?redirectUrl=${encodeURIComponent(redirectUrl)}`;
        vscode.env.openExternal(vscode.Uri.parse(loginUrl));

        // 等待用户登录
        return new Promise<UserInfo>((resolve, reject) => {
            const timeout = setTimeout(() => {
                server.close();
                reject(new Error('登录超时'));
            }, LOGIN_TIMEOUT_MS);

            server.on('close', () => {
                clearTimeout(timeout);
                if (this.userInfo) {
                    resolve(this.userInfo);
                } else {
                    reject(new Error('未获取到用户信息'));
                }
            });
        });
    }

    private async fetchUserInfo(oauthtoken: string): Promise<UserInfo> {
        const res = await axios.post(OAUTH_USERINFO_URL,
            `oauthtoken=${oauthtoken}`,
            { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
        );
        if (res.data && res.data.ret === 0) {
            return {
                ...res.data,
                oauthtoken
            };
        }
        throw new Error('获取用户信息失败');
    }

    public async logout(): Promise<void> {
        this.userInfo = null;
        await this.context.globalState.update('userInfo', null);

         // 清空所有任务缓存
        const allKeys = this.context.globalState.keys();
        for (const key of allKeys) {
        if (key.startsWith('taskList_') || key === 'taskList') {
            await this.context.globalState.update(key, []);
        }
      }
    }

    
} 

export async function isLoggedIn(context: vscode.ExtensionContext): Promise<boolean> {
    const userInfo = context.globalState.get<UserInfo>('userInfo');
    return !!userInfo;
} 